//
//  ImageItemView.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/1/30.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "ImageItemView.h"
//-------Phont----------
#import "ZLPhotoManager.h"
#import "ZLPhotoActionSheet.h"
//-------Phont----------

@interface ImageItemView() <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
    CGFloat itemWidth;
    
    CGFloat _selfHeight;
}

@property (weak, nonatomic) IBOutlet UICollectionView *colloctionView;

@property (copy, nonatomic) HeightBlock cellHeight;
@property (copy, nonatomic) ImageCountBlock imageCount;
@property (copy, nonatomic) ItemBlock didItemBlock;

@property (strong, nonatomic) NSMutableArray *selectAssetsModels;

// 相册选择
@property (strong, nonatomic)ZLPhotoActionSheet *ZLPhoto;

@end

@implementation ImageItemView

@synthesize imageArray = _imageArray;

- (void)awakeFromNib {
    [super awakeFromNib];
    self.itemCount =3;
    self.itemSpace =8;
    self.sectionEdgeInsets =UIEdgeInsetsMake(0, 0, 0, 0);
    self.maxCount =10;
    
    [_colloctionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];

    [TimerHandler performAfterDelay:0.1 handler:^{
        [self calculateItemWidth];
         _selfHeight =itemWidth +_itemSpace*2;
        [self.colloctionView reloadData];
    }];
}

- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray =[NSMutableArray array];
    }
    return _imageArray;
}

- (NSMutableArray *)selectAssetsModels {
    if (!_selectAssetsModels) {
        _selectAssetsModels =[NSMutableArray array];
    }
    return _selectAssetsModels;
}

- (void)calculateItemWidth {
    /// 内容总宽度
    CGFloat itemContentLength =CGRectGetWidth(self.frame)-(self.itemCount-1) *self.itemSpace-self.sectionEdgeInsets.left-self.sectionEdgeInsets.right;
    /// item宽度
    itemWidth = itemContentLength / (self.itemCount*1.0);
}

- (void)setImageArray:(NSMutableArray *)imageArray {
    _imageArray =imageArray;
    
    CGFloat itemContentLength =CGRectGetWidth(self.frame)-(self.itemCount-1) *self.itemSpace-self.sectionEdgeInsets.left-self.sectionEdgeInsets.right;
    itemWidth = itemContentLength / (self.itemCount*1.0);
    
    CGFloat nowHeight = ceilf((_imageArray.count+1)/(_itemCount*1.0)) *(itemWidth+_itemSpace) +_itemSpace;
    if (nowHeight !=_selfHeight) {
        _selfHeight =nowHeight;
        if (self.cellHeight) {
            self.cellHeight(nowHeight);
        }
    }
    if (_imageArray.count !=0) {
        [self.colloctionView reloadData];
    }
}

//有几个区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个区有几个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.imageArray.count>=self.maxCount) {
        return self.maxCount;
    }
    return self.imageArray.count +1;
}

//每个item之间的间距(竖) 设置最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return _itemSpace;
}
//每个item之间的间距(横) 设置最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return _itemSpace;
}
//定义每个Section 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return self.sectionEdgeInsets;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(itemWidth, itemWidth);
}
//重用cell
#pragma mark CollectionSelfCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *item =[collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    UIButton *button =(UIButton*)[item viewWithTag:1000];
    if (!button) {
        button =[UIButton buttonWithType:UIButtonTypeCustom];
        button.frame =CGRectMake(0, 8, itemWidth-8, itemWidth-8);
        [button addTarget:self action:@selector(imageButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.imageView.contentMode =UIViewContentModeScaleAspectFill;
        button.tag =1000;
        button.cornerRadius =1.0;
        [item addSubview:button];
        
        UIButton *deleteBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame =CGRectMake(itemWidth-16, 0, 16, 16);
        [deleteBtn setImage:[UIImage imageNamed:@"delete_icon"] forState:UIControlStateNormal];
        [deleteBtn addTarget:self action:@selector(deleteButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [item addSubview:deleteBtn];
    }
    button.frame =CGRectMake(0, 8, itemWidth-8, itemWidth-8);

    for (UIView *view in item.subviews) {
        if ([view isKindOfClass:[UIButton class]] && view.tag !=1000) {
            view.tag =indexPath.row+1;
        }
    }

    UIButton *deleteButton =(UIButton*)[item viewWithTag:indexPath.row+1];
    deleteButton.frame =CGRectMake(itemWidth-16, 0, 16, 16);
    if (indexPath.row >= self.imageArray.count) {
        deleteButton.hidden =YES;
        button.selected =YES;
        [button setImage:[UIImage imageNamed:@"paizhao-shangchuantupian"] forState:UIControlStateNormal];
    } else {
        if (self.isDelete) {
            deleteButton.hidden =NO;
        } else {
            deleteButton.hidden =YES;
        }
        button.selected =NO;
        id imageType =self.imageArray[indexPath.row];
        if ([imageType isKindOfClass:[UIImage class]]) {
            UIImage *image =(UIImage *)imageType;
            [button setImage:image forState:UIControlStateNormal];
        } else {
            NSString *imageString =(NSString *)imageType;
            if ([imageString hasPrefix:@"http"]) {
                [button sd_setImageWithURL:[NSURL URLWithString:imageString] forState:UIControlStateNormal placeholderImage:APP_DEFAULT_IMAGE];;
            } else {
                [button setImage:[UIImage imageNamed:imageString] forState:UIControlStateNormal];
            }
        }
    }
    return item;
}

- (void)imageButtonClick:(UIButton*)button {
    [self.window endEditing:NO];
    
    UICollectionViewCell *cell =(UICollectionViewCell*)button.superview;
    NSIndexPath *indexPath= [self.colloctionView indexPathForCell:cell];
    if (self.didItemBlock) {
        self.didItemBlock(indexPath.row, button.selected);
    }
    if (!button.selected) {
        return;
    }
    [SRActionSheet sr_showActionSheetViewWithTitle:@"选择资源" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"从相册选择", @"拍照"] selectSheetBlock:^(SRActionSheet *actionSheetView, NSInteger index) {
        if (index ==0) {
            [PermissionTool getPhotosPermission:^(NSInteger authStatus) {
                [PermissionTool returnMainThread:^{
                    if (authStatus ==1) {
                        __weak typeof(self)weakSelf = self;
                        self.ZLPhoto.arrSelectedAssets =self.selectAssetsModels;
                        [self.ZLPhoto showPhotoLibraryWithSender:[AppToast toast_currentShowTopVC]];
                        [self.ZLPhoto setSelectImageBlock:^(NSArray<UIImage *> * _Nullable images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
                            weakSelf.selectAssetsModels = [assets mutableCopy];
                            weakSelf.imageArray = images.mutableCopy;
                            [weakSelf backBlock];
                        }];
                    
                        self.ZLPhoto.cancleBlock = ^{
//                            NSLog(@"取消选择图片");
                        };
                        
                    } else {
                        [AppToast showFileWithString:@"您已拒绝访问相册, 请到手机 设置 隐私 中打开权限"];
                    }
                }];
            }];
        } else if (index ==1) {
            [PermissionTool getCamerasPermission:^(NSInteger authStatus) {
                if (authStatus ==1) {
                    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
                        [AppToast showFileWithString:@"您的设备不支持拍照, 请选择其它资源"];
                        return;
                    }
                    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    imagePicker.allowsEditing = YES;
                    imagePicker.delegate = self;
                    [[AppToast toast_currentShowTopVC] presentViewController:imagePicker animated:YES completion:nil];
                } else {
                    [AppToast showFileWithString:@"您已拒绝访问相机, 请到手机 设置 隐私 中打开权限"];
                }
            }];
        }
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (picker.sourceType ==UIImagePickerControllerSourceTypeCamera) {
        // 保存到系统相册
        [ZLPhotoManager saveImageToAblum:info[UIImagePickerControllerOriginalImage] completion:^(BOOL suc, PHAsset *asset) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (suc) {
                    // 同步选择数据
                    [self.selectAssetsModels addObject:asset];
                } else {
                    [AppToast showFileWithString:@"保存到系统相册失败"];
                }
            });
        }];
    }
    
    if (picker.allowsEditing) {
        [self.imageArray addObject:[info objectForKey:UIImagePickerControllerEditedImage]];
    } else {
        [self.imageArray addObject:[info objectForKey:UIImagePickerControllerOriginalImage]];
    }
    [self.colloctionView reloadData];
    [self backBlock];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)deleteButtonClick:(UIButton*)button {
    [self.imageArray removeObjectAtIndex:button.tag-1];
    if (button.tag-1 < self.selectAssetsModels.count) {
        [self.selectAssetsModels removeObjectAtIndex:button.tag-1];
    }
    [self.colloctionView reloadData];
    
    [self backBlock];
}

- (void)backBlock {
    NSInteger count =0;
    if (_imageArray.count>=self.maxCount) {
        count =self.maxCount;
    } else {
        count =_imageArray.count+1;
    }
    CGFloat nowHeight = ceilf(count/(self.itemCount*1.0)) *(itemWidth+_itemSpace) + _itemSpace;
    if (nowHeight !=_selfHeight) {
        _selfHeight =nowHeight;
        if (self.cellHeight) {  // 回调高度
            self.cellHeight(nowHeight);
        }
    }
    if (self.imageCount) {      // 回调image变化
        self.imageCount(self.imageArray);
    }
}

- (void)viewHeightChangeBlock:(HeightBlock)newBlock {
    self.cellHeight = newBlock;
}

- (void)imageCountChangeBlock:(ImageCountBlock)newBlock {
    self.imageCount = newBlock;
}

- (void)didCollectionItemBlock:(ItemBlock)newBlock {
    self.didItemBlock =newBlock;
}


- (ZLPhotoActionSheet *)ZLPhoto {
    if (!_ZLPhoto) {
        _ZLPhoto = [[ZLPhotoActionSheet alloc] init];
        _ZLPhoto.configuration.maxSelectCount = self.maxCount;
        _ZLPhoto.configuration.maxPreviewCount = 30;
        _ZLPhoto.configuration.navBarColor =APP_DEFAULT_COLOUR;
        _ZLPhoto.configuration.allowTakePhotoInLibrary =NO;
        _ZLPhoto.configuration.bottomBtnsNormalTitleColor =APP_DEFAULT_COLOUR;
    }
    return _ZLPhoto;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
